package com.tanhua.sso.service.impl;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.service.HuanXinService;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.service.UserService;

import com.tanhua.sso.vo.CountsVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Value("${jwt.secret}")
    private String secret;
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private HuanXinService huanXinService;
    @Autowired
    private SmsService smsService;

    @Override
    public String login(String mobile, String code) {
        String reidKey = "CHECK_CODE_" + mobile;
        String s = redisTemplate.opsForValue().get(reidKey);
        Boolean isNew = false; //是否为新注册
        if (s == null || !s.equals(code)) {
            return null;
        }
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().eq(User::getMobile, mobile);
        User user = userMapper.selectOne(qw);
        if (user == null) {
            // 该手机号未注册，进行注册操作
            User user1 = new User();
            user1.setMobile(mobile);
            user1.setPassword(DigestUtils.md5Hex(secret + "_123456"));// 默认密码
            userMapper.insert(user1);
            user = user1;
            isNew = true;

            huanXinService.register(user.getId());
        }
        //设置所需
        Map<String, Object> claims = new HashMap<>();
        claims.put("mobile", mobile);
        claims.put("id", user.getId());
        // 生成token
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, secret).compact();
        // 配置到redis中
        String redisTokenKey = "TOKEN_" + token;
        try {
            redisTemplate.opsForValue().set(redisTokenKey, MAPPER.writeValueAsString(user), Duration.ofDays(7));
            claims.clear();
            claims.put("userId", user.getId());
            claims.put("date", new Date());
            rocketMQTemplate.convertAndSend("tanhua-sso-login", claims);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isNew + "|" + token;
    }

    @Override
    public User queryUserByToken(String token) {
        try {
            String redisTokenKey = "TOKEN_" + token;
            String cacheData = this.redisTemplate.opsForValue().get(redisTokenKey);
            if (StringUtils.isEmpty(cacheData)) {
                return null;
            }
            // 刷新时间
            redisTemplate.expire(redisTokenKey, 2, TimeUnit.HOURS);
            return MAPPER.readValue(cacheData, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public CountsVo queryCounts() {
        com.tanhua.server.pojo.User user = UserThreadLocal.get();
        CountsVo countsVo = new CountsVo();

        countsVo.setEachLoveCount(this.userLikeApi.queryEachLikeCount(user.getId()));
        countsVo.setFanCount(this.userLikeApi.queryFanCount(user.getId()));
        countsVo.setLoveCount(this.userLikeApi.queryLikeCount(user.getId()));

        return countsVo;
    }

    @Override
    public boolean sendVerificationCode(String token) {
        User user = queryUserByToken(token);
        Map<String, Object> sendCheckCode = smsService.sendCheckCode(user.getMobile());
        int code = ((Integer) sendCheckCode.get("code")).intValue();
        return code == 3;
    }

    @Override
    public Boolean checkVerificationCode(String code, String token) {
        //查询到用户的手机号
        User user = queryUserByToken(token);
        if (null == user) {
            return false;
        }

        String redisKey = user.getMobile();
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (StringUtils.equals(value, code)) {
            //验证码正确
            this.redisTemplate.delete(redisKey);
            return true;
        }

        return false;
    }

    @Override
    public boolean savePhone(String token, String newPhone) {
        User user = queryUserByToken(token);
        return updatePhone(user.getId(), newPhone);
    }

    public boolean updatePhone(Long id, String newPhone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", newPhone);
        User user = this.userMapper.selectOne(queryWrapper);
        if (user != null) {
            // 改手机号已经存在
            return false;
        }
        user = new User();
        user.setId(id);
        user.setMobile(newPhone);
        return this.userMapper.updateById(user) > 0;
    }

}
